package sise.world.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.URISyntaxException;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.apache.log4j.Logger;

import sise.world.map.Field;

public class MapPanel extends JPanel {

	private static final long serialVersionUID = -4326412982459106315L;
	private static final Logger logger = Logger.getLogger(MapPanel.class);

	private JLabel[][] fields;
	private int fieldSize;

	public MapPanel(Field[][] map) {
		super();
		logger.info("Creating new MapPanel");
		fieldSize = 22;
		setLayout(new GridLayout(map.length, map[0].length));
		setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
		fields = getFieldsAsLabels(map);
		putFieldsOnPanel();
		setMaximumSize(new Dimension(map[0].length * fieldSize + 2, map.length * fieldSize + 2));
	}

	public void refresh(Field[][] map) {
		logger.info("Refresh MapPanel");
		fields = getFieldsAsLabels(map);
		putFieldsOnPanel();
		this.revalidate();
	}

	private JLabel[][] getFieldsAsLabels(Field[][] map) {
		logger.info("Changing fields to JLabels");
		JLabel[][] result = new JLabel[map.length][map[0].length];
		for (int row = 0; row < map.length; row++) {
			for (int col = 0; col < map[0].length; col++) {
				Icon icon = null;
				try {
					icon = map[row][col].getIcon();
				} catch (IOException | URISyntaxException e) {
					logger.error("Cannot retrieve the icon", e);
				}
				result[row][col] = new JLabel(icon);
				result[row][col].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
				result[row][col].setToolTipText(map[row][col].getToolTip());
			}
		}
		return result;
	}

	private void putFieldsOnPanel() {
		logger.info("Putting JLabels on panel");
		this.removeAll();
		for (JLabel[] row : fields) {
			for (JLabel field : row) {
				this.add(field);
			}
		}
	}

	public int getFieldSize() {
		return fieldSize;
	}

	public void setFieldSize(int fieldSize) {
		this.fieldSize = fieldSize;
	}

}
